package jwt

import (
	"github.com/gin-gonic/gin"
	"last/pkg/jwt"
	"last/pkg/respose"
)

// JwtAuth 鉴权中间件
func JwtAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求头中 token，实际是一个完整被签名过的 token；a complete, signed token
		tokenStr := c.GetHeader("Authorization")
		// fmt.Println(tokenStr)
		if tokenStr == "" {
			respose.Failed(c, "No token. You don't have permission!")
			//c.JSON(http.StatusForbidden, "No token. You don't have permission!")
			return
		}

		// 解析拿到完整有效的 token，里头包含解析后的 3 segment
		token, err := jwt.ParseToken(tokenStr)
		if err != nil {
			respose.Failed(c, "Invalid token! You don't have permission!")
			//c.JSON(http.StatusForbidden, "Invalid token! You don't have permission!")
			c.Abort()
			return
		}
		// 获取 token 中的 claims
		claims, ok := token.Claims.(*jwt.AuthClaims)
		if !ok {
			respose.Failed(c, "Invalid token!")
			//c.JSON(http.StatusForbidden, "Invalid token!")
			c.Abort()
			return
		}

		// 将 claims 中的用户信息存储在 context 中
		c.Set("userName", claims.UserName)

		// 这里执行路由 HandlerFunc
		c.Next()
	}
}
